﻿package com.sff.style {
	
	import com.sff.core.sff_internal;
	
	import flash.events.EventDispatcher;
	import flash.text.StyleSheet;
	import flash.utils.Dictionary;
	
	public class AdvanceStyleSheet extends EventDispatcher {
		
		private static const VAL	:RegExp = /0x/g; 
		private static const DOT	:RegExp = /\./g; 
		private static const SPACE	:RegExp = /\s/g;
		private static const COMMENT:RegExp = /\/\*(.)*\*\//g;
		
		private var styleSheet		:StyleSheet;
		private var dicStyle		:Dictionary;
		
		public function AdvanceStyleSheet() {
			this.dicStyle = new Dictionary();
			this.styleSheet = new StyleSheet();
		}		
		
		public function parseCSS(strCSS:String):void {
			
			//Remove all comment	
			strCSS = strCSS.replace(COMMENT, '');
			
			//Remove all space
			strCSS = strCSS.replace(SPACE, '');
			
			//Change 0x t #
			strCSS = strCSS.replace(VAL, '#');
			
			//parse css
			this.styleSheet.parseCSS(strCSS);
			
			var defaultStyleObject:Object = styleSheet.getStyle("*");
			var styleName:String;
			var styleObject:Object;
			var mergedObject:Object;
			var prop:String;
			
			var index:int = this.styleSheet.styleNames.length;
			var objStyle:Object;
			var strSelector:String;
			
			while (--index > -1) {
				strSelector = this.styleSheet.styleNames[index];
				objStyle = this.styleSheet.getStyle(strSelector);				
				
				strSelector = (strSelector.charAt(0) == ".") ? strSelector.substr(1) : strSelector; 
				dicStyle[strSelector] = createCssStyle(strSelector, objStyle);
			}			
		}
		
		private function createCssStyle(selector:String, objStyle:Object):CssStyle {			
			var cssStyle:CssStyle = new CssStyle(selector);
			cssStyle.sff_internal::setStyleSheet(this.styleSheet, objStyle);
			
			return cssStyle;
		}
		
		public function getStyle(selector:String):CssStyle {
			return dicStyle[selector.toLowerCase()];
		}
		
		sff_internal function getStyles(): Array {		
			var arrStyle:Array = [];			
			for (var key:String in dicStyle) {
				arrStyle.push(dicStyle[key]);	
			}			
			return arrStyle;
		}		
	}
}